package kzy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import kzy.common.BaseContext;
import kzy.common.R;
import kzy.entiy.Category;
import kzy.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author 大溪地
 * @create 2023年05月24日21:32
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;

	/**
	 * 分页查询Category
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/page")
	private R<Page> page(int page, int pageSize ){

		//构造分页构造器
		Page pageInfo = new Page(page,pageSize);
		log.info(page+","+pageSize+",");
		//构造条件构造器
		LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
		//添加过滤条件
//		queryWrapper.like(isNotEmpty(name),Category::getName,name);
		//添加排序条件
		queryWrapper.orderByAsc(Category::getSort);

		//执行查询
		categoryService.page(pageInfo,queryWrapper);
		return R.success(pageInfo);

	}


	@PostMapping()
	private R<String> addCategory(HttpServletRequest request,@RequestBody Category category ){
		//	获取创建人的id
		Long empId =(Long) request.getSession().getAttribute("employee");
		BaseContext.setCurrentId(empId);
		boolean save = categoryService.save(category);
		if(save){
			R.success("添加成功");

		}
		return R.success("添加失败");
	}

	/**
	 * 根据Category修改菜品
	 * @param request
	 * @param category
	 * @return
	 */
	@PutMapping()
	private R<String> modifyCategory(HttpServletRequest request,@RequestBody  Category category){
//	获取修改人的id
		Long empId =(Long) request.getSession().getAttribute("employee");
		BaseContext.setCurrentId(empId);
//		按Id更新
		categoryService.updateById(category);
		return R.success("修改完成");
	}

	/**
	 * 根据id删除菜品
	 * @param ids
	 * @return
	 */
//	@Transactional(rollbackFor = Exception.class)
	@DeleteMapping()
	public R<String> deleteCategory( Long ids){
		log.info("删除菜品的id："+ids);
//		categoryService.removeById(ids);
		categoryService.removeId(ids);
		return R.success("删除成功");
	}

	/**
	 * 查询所有的菜品
	 * @param type
	 * @return
	 */
	@GetMapping("/list")
	public R<List<Category>> list(Integer type){
		LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
		//添加过滤条件
		queryWrapper.eq(type!=null, Category::getType,type);
		queryWrapper.orderByAsc(Category::getSort);
		List<Category> list = categoryService.list(queryWrapper);

		return R.success(list);
	}




}
